package com.techwells.taco.net;



import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.techwells.learningkites.cache.SingleHttpClient;

/**
 * HTTP connection helper
 * @author
 *
 */
public class HttpConnectionUtils implements Runnable {
	private static final String TAG = HttpConnectionUtils.class.getSimpleName();
	public static final int DID_START = 0;
	public static final int DID_ERROR = 1;
	public static final int DID_SUCCEED = 2;

	private static final int GET = 0;
	private static final int POST = 1;
	private static final int PUT = 2;
	private static final int DELETE = 3;

	private static final int POST_FILE = 4;
	private static final int DELETE_ALL = 5;
	private static final int BITMAP = 6;

	private static String jsessionid;
	
	private String url;
	private int method;
	private Handler handler;
	private List<NameValuePair> data;
	private File file;
	private HashMap<String, String> cHash;
	
	
	private JsonObject jsonObj;
	private JSONObject jsonOBJ;

	private DefaultHttpClient httpClient;

	public HttpConnectionUtils() {
		this(new Handler());
	}

	public HttpConnectionUtils(Handler _handler) {
		handler = _handler;
	}
	
	public void create(int method, String url, List<NameValuePair> data) {
		Log.d(TAG, "method:"+method+" ,url:"+url+" ,data:"+data);
		this.method = method;
		this.url = url;
		this.data = data;
		ConnectionManager.getInstance().push(this);
	}
	
	public void createFile(int method, String url, File file) {
		this.method = method;
		this.url = url;
		this.file = file;
		ConnectionManager.getInstance().push(this);
	}

	public void get(String url) {
		create(GET, url, null);
	}

	public void post(String url, List<NameValuePair> data) {
		create(POST, url, data);
	}
	public void postFile(String url, File data) {
		createFile(POST_FILE, url, data);
	}
	
	
	
	public void put(String url, List<NameValuePair> data) {
		create(PUT, url, data);
	}

	public void delete(String url) {
		create(DELETE, url, null);
	}
	
	public void deleteAll(String url, List<NameValuePair> data) {
		create(DELETE_ALL, url, data);
	}

	public void bitmap(String url) {
		create(BITMAP, url, null);
	}

	@Override
	public void run() {
		handler.sendMessage(Message.obtain(handler, HttpConnectionUtils.DID_START));
		httpClient = SingleHttpClient.getInstance();
		HttpConnectionParams
				.setConnectionTimeout(httpClient.getParams(), 6000);
		/*cHash = SingleHttpClient.getCookieHash();
		if(cHash != null){
			CookieStore cookieStore = httpClient.getCookieStore();
			for(String key:cHash.keySet()){
				
				Cookie cookie = new BasicClientCookie(key, cHash.get(key));
				cookieStore.addCookie(cookie);
			}

			httpClient.setCookieStore(cookieStore);
			
			
		}*/
				

		
		
/*        if(null != Constant.PHPSESSID){
        	httpClient.getParams().setParameter("Cookie", "_SamsoniteAPI_session=" + Constant.PHPSESSID);
        }*/
		try {
			HttpResponse response = null;
			switch (method) {
			case GET:
				Log.d("jsessionid执行成功", jsessionid);
				HttpGet httpGet = new HttpGet(url);  
				httpGet.setHeader("Cookie", "JSESSIONID=" + jsessionid);
				response = httpClient.execute(httpGet);
				Log.d("返回code", ""+response.getStatusLine().getStatusCode());
				break;
			case POST:
				Log.d("发送urllllllllllllll", url);
				HttpPost httpPost = new HttpPost(url);								
				httpPost.setHeader("Cookie", "JSESSIONID=" + jsessionid); 
				HttpEntity entity = new UrlEncodedFormEntity(data,HTTP.UTF_8);
		
				httpPost.setEntity(entity);
				//String token = "";
				/*
				String token = TorqueDevice.getInstance().getUserToken();
				
				HashMap<String, String> hashMap = new HashMap<String, String>();
				hashMap.put("userToken", token);
				Gson gson = new Gson();
				String tokenGson = gson.toJson(hashMap);

				httpPost.addHeader("torquehead", ""+ tokenGson);
				*/
				
				/*
				SSLContext sslContext = null;
				SSLSocketFactoryEx socketFactoryEx = null;
				try {
					socketFactoryEx = new SSLSocketFactoryEx(null);
				} catch (Exception e) {
					e.printStackTrace();
				}
				sslContext = socketFactoryEx.sslContext;
				if (sslContext != null) {
					HttpsURLConnection.setDefaultSSLSocketFactory(sslContext
							.getSocketFactory());
				}
				*/
				
				
				response = httpClient.execute(httpPost);
				Log.d("返回code", ""+response.getStatusLine().getStatusCode());
				
				jsonObj = new JsonObject();
		        jsonObj.addProperty("state", response.getStatusLine().getStatusCode());
		        
		        List<Cookie> cookies = httpClient.getCookieStore().getCookies();  
		        if (cookies.isEmpty()) {  
		        Log.i(TAG, "-------Cookie NONE---------");  
		        } else {                 
		        for (int i = 0; i < cookies.size(); i++ ) {  
		        //保存cookie  
		        Cookie cookie = cookies.get(i);
		        jsessionid = cookies.get(i).getValue();
		        Log.d(TAG, cookies.get(i).getName() + "=" + cookies.get(i).getValue() );  
		        }
		        }
//		        Header[] header = response.getAllHeaders();
//		        for (int i = 0; i < header.length; i++) {
//		        	Log.d("返回code", ""+header[1].getValue());
//				}
		        /*
		        CookieStore mCookieStore = httpClient.getCookieStore();
                List<Cookie> cookies = mCookieStore.getCookies();
                for (int i = 0; i < cookies.size(); i++) {
                     //这里是读取Cookie['PHPSESSID']的值存在静态变量中，保证每次都是同一个值
                	Log.d("返回code", cookies.get(i).getValue());
                        break;
                    }
                    */	
				
//		        jsonOBJ = new JSONObject();
//		        jsonOBJ.put("status", response.getStatusLine().getStatusCode());
				
/*				if(true){
					CookieStore cookieStore = httpClient.getCookieStore();
					cHash = new HashMap<String, String>();
					for(Cookie cookie : cookieStore.getCookies()){ 
						cHash.put(cookie.getName(), cookie.getValue());						  
			        } 
					SingleHttpClient.setCookieHash(cHash);
					
					httpClient.setCookieStore(cookieStore);
				}*/
				
				break;
				
			case DELETE_ALL:
				
				MyHttpDelete httpDelete = new MyHttpDelete(url);								
				
				HttpEntity deleteEntity = new UrlEncodedFormEntity(data);
		
				
				httpDelete.setEntity(deleteEntity);
				response = httpClient.execute(httpDelete);
				break;
				
				
			case POST_FILE:
				HttpPost httpPostFile = new HttpPost(url);
								
				MultipartEntity mpEntity = new MultipartEntity();
			    ContentBody cbFile = new FileBody(file);
			    mpEntity.addPart("myfiles", cbFile); 
				
			    httpPostFile.setEntity(mpEntity);
			    
				response = httpClient.execute(httpPostFile);
				

				break;
				
			case PUT:
				HttpPut httpPut = new HttpPut(url);
				httpPut.setEntity(new UrlEncodedFormEntity(data,HTTP.UTF_8));
				response = httpClient.execute(httpPut);
				break;
			case DELETE:
				response = httpClient.execute(new HttpDelete(url));
				break;
			case BITMAP:
				response = httpClient.execute(new HttpGet(url));
				processBitmapEntity(response.getEntity());
				break;
			}
			if (method < BITMAP)
				processEntity(response.getEntity());
			
/*                String cookieVal = (String)httpClient.getParams().getParameter("Set-Cookie");
                //��ȡsession
                if(cookieVal != null){
                	Constant.PHPSESSID = cookieVal.substring(cookieVal.indexOf("=") + 1, cookieVal.indexOf(";"));
                }*/
			
		} catch (Exception e) {
			handler.sendMessage(Message.obtain(handler,
					HttpConnectionUtils.DID_ERROR, e));
		}
		  ConnectionManager.getInstance().didComplete(this);
	}

	private void processEntity(HttpEntity entity) throws IllegalStateException,
			IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(entity
				.getContent()));
		
		
		
//		String line, result = "";
////		result += jsonObj.toString();
//		while ((line = br.readLine()) != null){
//			result += line;
//				try {
//					JSONObject returnJson = new JSONObject(result.trim());
//					jsonObj.addProperty("code", returnJson.getString("code"));
//				} catch (JSONException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
//		}
//		result = jsonObj.toString();
//		Message message = Message.obtain(handler, DID_SUCCEED, result);
//		handler.sendMessage(message);
		String line, result = "";
		while ((line = br.readLine()) != null){
			result += line;
			try {
				JSONObject returnJson = new JSONObject(result.trim());
				Log.d("返回jsonnnnnnnnnnnnnnnnnnnnnnnnnn", returnJson.toString());
				jsonObj.addProperty("code", returnJson.getString("code"));
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		result = jsonObj.toString();
		Log.d("返回json", result);
		Message message = Message.obtain(handler, DID_SUCCEED, result);
		handler.sendMessage(message);
	}

	private void processBitmapEntity(HttpEntity entity) throws IOException {
		BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
		Bitmap bm = BitmapFactory.decodeStream(bufHttpEntity.getContent());
		handler.sendMessage(Message.obtain(handler, DID_SUCCEED, bm));
	}

	
	
}
